<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */

class SettingsController extends BackOfficeController
{
    public function actionIndex(){
        $criteria = new CDbCriteria();
        $criteria->condition = "Visible = 1";
        $criteria->order = 'GroupName, Ordering';
        
        $module = $this->get('module','');
        if ($module == 'Core') $module = '';
//        if (($module = $this->get('module','')) != '')
//        {
            $criteria->condition .= ' AND Module = :Module';
            $criteria->params = array(':Module' => $module);
//        }
        
        $this->data['params'] = Setting::model()->findAll($criteria);
        $this->data['module'] = $module;
        
        $this->render('Settings', $this->data);    
    }
    
    public function actionSave(){
        $module = $this->post('Module', '');
        
        if (Yii::app()->request->isPostRequest){
            
            $this->message = 'Your new configuration is updated successfully.';
            //POST data   
            foreach($_POST as $key => $value){
                $param = Setting::model()->find('Name = :Param AND Module = :Module',array(':Param' => $key, ':Module' => $module));
                if (is_null($param)) continue;
                                
                $param->Value = $value;
                if (!$param->validate()){
                    ErrorHandler::logError($param->getError('Value'));
                    $this->message = '';
                }else
                    $param->save();
            }                              
            
            //FILE upload if any
            foreach($_FILES as $key => $file){
                /**
                * If enctype='multipart/form-data' has file fiels, $_FILES always
                * has information related to file fields. We have to check if
                * each field has file uploaded or not
                */
                if ($file['error'] == UPLOAD_ERR_NO_FILE) continue;
                
                $param = Setting::model()->find('Name = :Param',array(':Param' => $key));
                if (is_null($param)) continue; //Not match any setting param
                
                /**
                * Set param value to $file as normally an upload file param should have
                * a writer Service to save file and return filepath as the final value
                */                    
                $param->Value = $file;
                if (!$param->validate()){
                    ErrorHandler::logError($param->getError('Value'));
                    $this->message = '';
                }else
                    $param->save();
            }
            
            //Cms::service('Cms/Settings/db2php', array('Module' => $module));
        }
        $params = array();
        if ($module)
            $params = array('module' => $module);
        $this->redirect($this->createUrl("/Core/settings", $params));    
    }
    
    public function __construct($id, $module = null){
        parent::__construct($id, $module);
        Yii::app()->layout = 'module';        
    }
    
    public function actionList()
    {
        $module = '';
        if ($this->post('module'))
        {
            $module = $this->post('module');
        }
        if ($module == 'System')
        {
            $module = '';
        }
        $criteria = new CDbCriteria();
//        $criteria->condition = "Visible = 1";
        $criteria->condition .= " Module = :Module";
        $criteria->order = 'GroupName, Ordering';
        $criteria->params = array(':Module' => $module);
        $params = Setting::model()->findAll($criteria);
        if ($module == '')
        {
            $module = 'System';
        }
        // Group by GroupName
        $tmp = array();
        foreach($params as $p)
        {
            $key = 'Ungroupped';
            if (! empty($p->GroupName)) $key = $p->GroupName;
            $tmp[$key][] = $p;
        }
        $params = $tmp;
        
        // Get all modules
        $sql = "
                SELECT DISTINCT Module 
                FROM settings 
                ORDER BY Module
                ";
        $conn = Yii::app()->db;
        $command = $conn->createCommand($sql);
        $modules = $command->queryAll();
        
        $this->render('List', array(
                                'params' => $params,
                                'module' => $module,
                                'modules' => $modules,
                                ));
    }
    
    /**
    * Edit action
    * 
    */
    public function actionCreate()
    {
        $param = new Setting();
        
        // Get all modules
        $modules = array();
        $tmp = array_keys(Yii::app()->modules);
        sort($tmp);
        foreach($tmp as $m)
        {
            $modules[]['Name'] = $m;
        }
        $modules['System']['Name'] = 'System';
        $this->render('Edit', array(
                                'param' => $param,
                                'modules' => $modules
                                ));
    }
    
    public function actionEdit()
    {
        $module = $name = '';
        if ($this->get('Module', '') != '')
        {
            $module = $this->get('Module');
        }
        if ($this->get('Name', '') != '')
        {
            $name = $this->get('Name');
        }
        $param = Setting::model()->findByPk(array('Module' => $module, 'Name' => $name));
        if (empty($param))
        {
            throw new CHttpException(404, 'Parameter no found');
        }
        if ($param->Module == '') $param->Module = 'System';
        // Get all modules
        $modules = array();
        $tmp = array_keys(Yii::app()->modules);
        sort($tmp);
        foreach($tmp as $m)
        {
            $modules[]['Name'] = $m;
        }
        $modules['System']['Name'] = 'System';
        
        $this->render('Edit', array(
                                'param' => $param,
                                'modules' => $modules,
                                'action' => 'updateParam',
                                ));
    }
    
    
    public function actionUpdateParam()
    {
        # Make sure this action can be requested only by POST
        if (Yii::app()->request->isPostRequest)
        {
            # update param
            $result = FSM::run('Core.Settings.update', $_POST);
            if (! $result->hasErrors())
            {
                $this->message = Yii::t('Parameter', 'PARAMETER_UPDATE_SUCCESSFUL');
            }
            
            //Rebuild cache
            FSM::run('Core.Settings.rebuildCache',array());
            
            $this->redirect($this->createUrl('/Core/settings/list'));
        }
    }
    
    /**
    * Save action
    * 
    */
    public function actionSaveNewParam()
    {
        # Make sure this action can be requested only by POST
        if (Yii::app()->request->isPostRequest)
        {
            # create new param
            $result = FSM::run('Core.Settings.create', $_POST);
            if (! $result->hasErrors())
            {
                $this->message = Yii::t('Parameter', 'PARAMETER_CREATE_SUCCESSFUL');
            }
            // Rebuild cache
            FSM::run('Core.Settings.rebuildCache',array());
            
            $this->redirect($this->createUrl('/Core/settings/create'));
        }
    }
    
    /**
    * Rebuild cache files for all module settings
    */
    public function actionRebuildCache()
    {
        $result = Cms::service('Cms/Settings/rebuildCache',array());
        $this->message = 'Cache is updated for pages, categories, system and all modules settings.';
        $this->redirect($this->createUrl('/BackOffice/admin/modules/dashboard', array('module' => 'Cms')));
    }
    
    public function actionDelete()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $result = FSM::run('Core.Settings.delete', $_POST);
            echo $result->toJson();
            exit;
        }
    }
    
    public function actionReorder()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $result = FSM::run('Core.Settings.reorder', $_POST);
            echo $result->toJson();
            exit;
        }
    }
}
?>
